from django.http import HttpResponse
from django.shortcuts import render

from view_demo.c.form import PersonInfoForm
from view_demo.c.models import PersonInfo


def index(request):
    return render(request, 'c/c_redirect_view.html')


from django.views.generic.base import RedirectView


class RedirectViewDemo(RedirectView):
    # 设置属性
    permanent = False
    url = None
    pattern_name = 'index'
    query_string = True

    def get_redirect_url(self, *args, **kwargs):
        print('This is get_redirect_url')
        return super().get_redirect_url(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        print(request.META.get('HTTP_USER_AGENT'))
        return super().get(request, *args, **kwargs)


from django.views.generic.base import TemplateView


class TemplateViewDemo(TemplateView):
    template_name = 'c/c_template_view.html'
    template_engine = None
    context_type = None
    extra_context = {'title': 'This is GET'}

    # 重新定义模版上下文的获取方式
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['value'] = 'i am my django'
        return context

    def post(self, request, *args, **kwargs):
        """
        定义HTTP 的post 请求处理方法
        参数request 代表http请求信息
        若路由设有变量，则可从参数kwargs里获取
        """
        self.extra_context = {'title': 'This is POST'}
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context)


from django.views.generic import ListView


class ListViewDemo(ListView):
    """
    关键知识点说明：
    模板变量：{{ 变量名 }} 格式的内容会被 Django 模板引擎替换为对应的值，例如：
    {{ title }} 来自视图中extra_context = {'title': '人员信息表'}
    {{ personinfo_list }} 是 ListView 默认生成的查询集列表（模型名小写_list）
    {{ page_obj }} 是分页对象，包含分页相关的所有信息
    模板标签：{% 标签名 %} 用于实现逻辑控制，如：
    {% for ... %}：循环遍历列表
    {% if ... %}：条件判断
    {% url 'person_info' %}：根据 URL 名称生成对应的 URL 路径
    分页相关变量（来自 Django 的 Paginator）：
    is_paginated：布尔值，判断是否需要分页
    page_obj.has_previous：是否有上一页
    page_obj.previous_page_number：上一页的页码
    page_obj.has_next：是否有下一页
    page_obj.next_page_number：下一页的页码
    page_obj.number：当前页码
    page_obj.paginator.num_pages：总页数

    """
    # 设置模板文件
    template_name = 'c/c_list_view.html'
    # 设置模型外的数据
    extra_context = {'title': '人员信息表'}
    # 模型数据
    queryset = PersonInfo.objects.all()
    # 每页展示一条数据
    paginate_by = 1
    # 模板上下文
    # context_object_name = 'personinfo_list'


from django.views.generic.detail import DetailView


class DetailViewDemo(DetailView):
    template_name = 'c/c_detail_view.html'
    extra_context = {'title': '人员信息表'}
    slug_field = 'age'
    slug_url_kwarg = 'age'
    pk_url_kwarg = 'pk'
    model = PersonInfo


# Todo edit
from django.views.generic.edit import FormView
from django.urls import reverse_lazy


class FormViewDemo(FormView):
    initial = {'name': 'Betty', 'age': 20}
    template_name = 'c/c_form_view.html'
    success_url = reverse_lazy('result')
    form_class = PersonInfoForm
    extra_context = {'title': '人员信息表'}


def result(request):
    return HttpResponse('Success')


from django.views.generic.edit import CreateView


class CreateViewDemo(CreateView):
    # 表单生成方式
    model = PersonInfo
    # 为表单字段设置初始默认值
    initial = {'name': 'Betty', 'age': 20}
    # 指定单模版
    template_name = 'c/c_create_view.html'
    success_url = reverse_lazy('result')
    # fields设置模型字段，从而生成表单字段
    # fields = ['name', 'age']
    form_class = PersonInfoForm
    extra_context = {'title': '人员信息表'}

    # 在这里定义form_valid方法
    def form_valid(self, form):
        # 调试输出表单数据
        print("表单数据:", form.cleaned_data)
        # 调用父类的form_valid方法，确保数据能正常保存
        return super().form_valid(form)

    def form_invalid(self, form):
        """表单验证失败后的处理"""
        print("表单验证失败")
        print("错误信息:", form.errors)
        return super().form_invalid(form)


from django.views.generic.edit import UpdateView


class UpdateViewDemo(UpdateView):
    model = PersonInfo
    template_name = 'c/c_update_view.html'
    success_url = reverse_lazy('result')
    fields = ['name', 'age']
    slug_url_kwarg = 'age'
    slug_field = 'age'
    context_object_name = 'personinfo'
    extra_context = {'title': '人员信息表'}


from django.views.generic.edit import DeleteView


class DeleteViewDemo(DeleteView):
    model = PersonInfo
    template_name = 'c/c_delete_view.html'
    success_url = reverse_lazy('result')
    context_object_name = 'personinfo'
    extra_context = {'title': '人员信息表'}
